<template>
  <!-- <el-row  :gutter="2" >
    <el-col  :span="20"> -->
      <!-- 卡片容器，用于展示表格和分页 -->
   <el-card style="max-width: 1100px">
    <!-- 输入框，用于输入原材料名称 -->
    <el-input v-model="name" style="width: 240px" placeholder="请输入原材料名称" />
    <!-- 查询按钮，点击触发getList方法进行数据查询 -->
    <el-button type="primary" @click="getList">查询</el-button>

    <!-- 新增按钮，点击触发add方法进行新增操作 -->
    <el-button type="primary" @click="add">新增</el-button>
    <!-- table多选表单，展示原材料列表 -->
    <el-table :data="tableData" style="width: 100%">
      <!-- 多选框，用于选中表格中的行 -->
      <el-table-column type="selection" width="55" />

      <!-- 显示原材料id的列 -->
      <el-table-column property="id" label="原材料id" width="120px"/>
      <!-- 显示原材料名称的列 -->
      <el-table-column property="name" label="原材料" width="120px" />
      <!-- 显示原材料类型的列 -->
      <el-table-column label="类型" width="120px">
        <template #default="{ row }">
            <span>
                <!-- 调用getCategoryLabel方法根据分类值显示对应的标签 -->
                {{ getCategoryLabel(row.category) }}
            </span>
        </template>
      </el-table-column>
      <!-- 显示原材料数量的列 -->
      <el-table-column property="number" label="数量" width="120px"/>
      <!-- 显示原材料价格的列 -->
      <el-table-column property="price" label="单价" width="120px"/>
      <!-- 显示原材料供应商的列 -->
      <el-table-column property="supplierName" label="供应商" width="120px"/>

      <!-- 显示最后修改的时间 -->
      <el-table-column property="updateTime" label="更新日期" width="120px"/>
      <!-- 操作列，包含编辑和删除按钮 -->
      <el-table-column label="操作" width="200px">
        <template #default="scope">
          <!-- 编辑按钮 -->
          <el-button type="primary"  @click="edit(scope.row)">编辑</el-button>
          <!-- 删除按钮 -->
          <el-button type="danger" @click="del(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页模块，用于切换页面和设置每页显示数量 -->
    <el-pagination
      v-model:current-page="PageNum"
      v-model:page-size="PageSize"
      :page-sizes="[8, 10, 12, 14]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </el-card>
<!-- 
  </el-col> -->



  <!-- <el-col  :span="4"> -->
         
 

  <el-dialog
        v-model="centerDialogVisible"
       :title="isEdit ? '编辑原材料' : '新增原材料'"
        width="500"
        align-center
     
      >
    <el-form :model="formData" label-width="auto"
     style="max-width: 600px"

      :rules="rules"
     >
      <el-form-item label="名称" prop="name">
        <el-input v-model="formData.name" />
      </el-form-item>
      <el-form-item label="类型" prop="category">
        <el-select v-model="formData.category">
          <el-option :value="0" label="原材料" />
          <el-option :value="1" label="半成品" />
          <el-option :value="2" label="成品" />
        </el-select>
      </el-form-item>
      <el-form-item label="数量" prop="number">
        <el-input v-model="formData.number" />
      </el-form-item>
      <el-form-item label="单价" prop="price">
        <el-input v-model="formData.price" />
      </el-form-item>
      <el-form-item label="供应商" prop="supplier">
          <el-select v-model="formData.supplier">
            <el-option
              v-for="item in supplierlist"
              :key="item.supplierId"
              :label="item.supplierName"
              :value="item.supplierId"
            />
          </el-select>
      </el-form-item>

      <el-form-item label="备注" prop="remark"
      >
      <el-input
        v-model="tableData.remark"
        style="width: 420px"
        :autosize="{ minRows: 2, maxRows: 4 }"
        type="textarea"
        placeholder="说一下采购原因"
      />

      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit"   :loading="submitting" >
        {{ submitting ? '提交中...' : isEdit ? '保存修改' : '立即创建' }}
      </el-button>
      </div>
    </template>
  </el-dialog>

  </template>

  <script lang="js" setup>
  // 引入Vue的响应式和生命周期钩子
  import { ref, reactive,onMounted } from 'vue'
  // 引入获取库存数据的接口
  import { getstash,deletestash,addstash,updatestash,getSupplierlist } from '@/api/stash'

  import * as echarts from 'echarts'
  // 定义输入框绑定的响应式变量
  const name = ref('')
  // 定义表格数据的响应式变量
  const tableData = ref([])
  // 定义当前页码的响应式变量
  const PageNum = ref(1)
  // 定义每页显示数量的响应式变量
  const PageSize = ref(8)
  // 定义数据总数的响应式变量
  const total = ref(0)

  const submitting = ref(false)

  const isEdit = ref(false)

  // 图表




// 重构后的表单数据
  const formData = reactive({
    id: null,
    name: '',
    category: 0,
    number: null,
    price: null,
    supplier: 0
  })
  const centerDialogVisible = ref(false)

  onMounted(() => {

    getList(),
    getsupplierlist()
  })

  
  const getList = async() => {
  
    const res = await getstash({
        name: name.value,
        PageNum: PageNum.value,
        PageSize: PageSize.value
     })

    if (res.data.code === "200") {
      tableData.value = res.data.data.list
      total.value = res.data.data.total
    }
  }

  const supplierlist=ref([])

  const getsupplierlist = async() =>  {
    const res = await getSupplierlist()
    if (res.data.code === "200") {
      supplierlist.value = res.data.data
      console.log('供应商'+supplierlist.value);
      
    }
  }
  const handleSizeChange = (val) => {
    PageSize.value = val
    getList()
  }


  const handleCurrentChange = (val) => {
    PageNum.value = val
    getList()
  }
 
  const getCategoryLabel = (category) => {
    if (category === 0) {
      return '原材料';
    } else if (category === 1) {
      return '半成品';
    } else if (category === 2) {
      return '成品';
    }
    return '未知类型';
  }

  const del = (row) => {  
    ElMessageBox.confirm(
      '确定要删除数据吗？',
      '警告',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(async () => {  
      try {
        await deletestash(row.id)
        ElMessage({
        type: 'success',
        message: '删除成功',
      })
        } catch (error) {
          ElMessage({
          type: 'error',
          message: '删除失败',
       })
    }
   await getList()  
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '取消删除成功',
    })
  })
}
  //添加表单
  const add = () => {
    isEdit.value = false
    resetForm()
    centerDialogVisible.value = true
  }

  const edit=(row) => {
    isEdit.value = true
    formData.id = row.id
    formData.name = row.name
    formData.category = row.category
    formData.number = row.number
    formData.price = row.price
    formData.supplier = row.supplier

    centerDialogVisible.value = true 
  }
  

  // 提交表单
  const handleSubmit = async () => {
   try{
    if (isEdit.value) {
      await updatestash(formData)
      ElMessage({
        type: 'success',
        message: '修改成功',
      })   
    }else{
      await addstash(formData)
      ElMessage({
        type:'success',
        message: '添加成功',
      })
    }
    centerDialogVisible.value = false
    await getList()
   } catch (error) {
    ElMessage({
      type: 'error',
      message: '提交失败'+error.message,
    }) 
   }finally {
    submitting.value = false
  }
  }

  // 重置表单
const resetForm = () => {
   Object.assign(formData, {
    id: null,
    name: '',
    category: 0,
    number: null,
    price: null,
    supplier: '' 
   }) 
  }

  // 添加验证规则
const rules = reactive({
  name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
  category: [{ required: true, message: '请选择类型', trigger: 'change' }],
  number: [
    { required: true, message: '数量不能为空' },
    { type: 'number', message: '必须为数字值' }
  ],
  price: [
    { required: true, message: '单价不能为空' },
    { type: 'number', message: '必须为数字值' }
  ]
})
  </script>

  <style scoped>
  /* 设置按钮的左外边距 */
  .el-button {
    margin-left: 10px;
  }
  </style>